package com.tengju.user.infrastructure.shared;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpClientUtil {

    /**
     * HTTP的Post请求方式
     * @param strUrl 访问地址
     * @param param 参数字符串
     * */
    public static String doPost(String strUrl, String param) {
        // 返回结果定义
        String returnStr = null;
        URL url = null;
        HttpURLConnection httpUrlConnection = null;
        try {
            url = new URL(strUrl);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            // post方式
            httpUrlConnection.setRequestMethod("POST");
            httpUrlConnection.connect();
            //POST方法时使用
            byte[] byteParam = param.getBytes(StandardCharsets.UTF_8);
            DataOutputStream out = new DataOutputStream(httpUrlConnection.getOutputStream());
            out.write(byteParam);
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpUrlConnection.getInputStream(), StandardCharsets.UTF_8));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpUrlConnection != null) {
                httpUrlConnection.disconnect();
            }
        }
        return returnStr;
    }

    /**
     * 将map型转为请求参数型
     *
     * @param data 数据
     * @return {@link String}
     */
    public static String urlArgsEncode(Map<String, Object> data) {
        StringBuilder apiStore = new StringBuilder();
        for (Map.Entry<String, Object> i : data.entrySet()) {
            apiStore.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"", StandardCharsets.UTF_8)).append("&");
        }
        return apiStore.toString();
    }
}
